package utility;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.FileReader;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * Id & its order
 * @author D
 *
 */

public class IdDict {
	
	private Map<Integer, Integer> dict;
	
	public IdDict() {
		dict = new HashMap<Integer, Integer>();
	}
	
	public IdDict(int i) {
		dict = new TreeMap<Integer, Integer>();
	}
	
	public void addRecord(Integer key, Integer value) {
		dict.put(key, value);
	}
	
	public void rmRecord(Integer key) {
		dict.remove(key);
	}
	
	public Integer dictValue(Integer key) {
		return dict.get(key);
	}
	
	public void loadDict(String inPath) {
		dict.clear();
		String str;
		String[] tokens;
		try {
			BufferedReader in = new BufferedReader(new FileReader(inPath));
			while((str = in.readLine()) != null) {
				tokens = str.split("\t");
				addRecord(Integer.parseInt(tokens[0]), Integer.parseInt(tokens[1]));
			}
			System.out.print(dict.size());
			System.out.println(" record load success");
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void loadAntiDict(String inPath) {
		dict.clear();
		String str;
		String[] tokens;
		try {
			BufferedReader in = new BufferedReader(new FileReader(inPath));
			while((str = in.readLine()) != null) {
				tokens = str.split("\t");
				addRecord(Integer.parseInt(tokens[1]), Integer.parseInt(tokens[0]));
			}
			System.out.print(dict.size());
			System.out.println(" record load success");
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void writeSet(String outPath) {
		try {
			BufferedWriter out = new BufferedWriter(new FileWriter(outPath));
			for(Integer key : dict.keySet()) {
				out.write(key.toString());
				out.newLine();
			}
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void writeDict(String outPath) {
		if(dict instanceof TreeMap) {
			int i = 0;
			try {
				BufferedWriter out = new BufferedWriter(new FileWriter(outPath));
				for(Integer key : dict.keySet()) {
					out.write(key.toString());
					out.write("\t");
					i++;
					out.write(Integer.toString(i));
					out.newLine();
				}
				out.flush();
				out.close();
				System.out.print(dict.size());
				System.out.println(" record write success");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		else {
			System.out.println("Unsorted record, fail to write...");
		}
	}
	
}
